import CryptoJS from 'crypto-js';

const SECRETKEY = CryptoJS.enc.Hex.parse('ym-upload-video-key-1685500690141');

// 加密
export const encrypt: (data: any) => string = (data) => {
  if (typeof data === 'object') {
    try {
      // eslint-disable-next-line no-param-reassign
      data = JSON.stringify(data);
    } catch (err) {
      console.log('encrypt error:', err);
    }
  }

  const cipherJson = CryptoJS.AES.encrypt(data, SECRETKEY, {
    iv: SECRETKEY, //偏移量
    mode: CryptoJS.mode.CFB, //加密模式
    padding: CryptoJS.pad.AnsiX923, //填充方式
  });

  return cipherJson.toString();
};

// 解密
export const decrypt: (cipherText: string) => object = (cipherText) => {
  const bytes = CryptoJS.AES.decrypt(cipherText, SECRETKEY, {
    iv: SECRETKEY, //偏移量
    mode: CryptoJS.mode.CFB, //加密模式
    padding: CryptoJS.pad.AnsiX923, //填充方式
  });
  return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
};
